//
//  RightViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/2/1.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "RightViewController.h"
#import "LoginViewController.h"
#import "OwnerCompleteViewController.h"
#import "ShipperCompleteViewController.h"
#import "LogisticsCompleteViewController.h"
#import "AboutUsViewController.h"
#import "FeedbackViewController.h"
#import "AppShareViewController.h"
#import "ProtocolViewController.h"
#import "NewsListViewController.h"
#import "UserCenterViewController.h"
#import "DDMenuController.h"

@interface RightViewController (){
    AppDelegate *app;
    NSArray *_dataArray;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation RightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [self.tableView setTableFooterView:view];

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"RightMenu"] != nil) {
        NSError *error = nil;
        
        id datadic = [NSJSONSerialization
                      
                      JSONObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"RightMenu"]
                      
                      options:NSJSONReadingMutableLeaves
                      
                      error:&error];
        _dataArray = datadic;
    }
    if (_dataArray.count == 0 || [[GlobalData sharedGlobalData] isNewLeft]) {
        [self getRightMenu];
    }
    [self getAccountInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAccountInfo) name:@"AccountInfo" object:nil];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_footerView setFrame:CGRectMake(0, self.view.frame.size.height - 43, self.view.frame.size.width, 43)];

}

- (void)getAccountInfo{
    if ([[GlobalData sharedGlobalData] userinfoDic] != nil) {
        _accountLabel.hidden = NO;
        _typeLabel.hidden = NO;
        _accountLabel.text = [[GlobalData sharedGlobalData] userinfoDic][@"UserName"];
        switch ([[[GlobalData sharedGlobalData] userinfoDic][@"UserType"] intValue]) {
            case 0:
                _typeLabel.text = @"车主";
                break;
            case 1:
                _typeLabel.text = @"货主";
                break;
            case 2:
                _typeLabel.text = @"物流公司";
                break;
                
            default:
                break;
        }
        _loginBtn.hidden = YES;
    }else{
        _accountLabel.hidden = YES;
        _typeLabel.hidden = YES;
        _loginBtn.hidden = NO;
    }
}

- (IBAction)gotoLoginView{
    UINavigationController *menuController = (UINavigationController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    
    LoginViewController *vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
    [menuController pushViewController:vc animated:YES];
}

#pragma mark -请求接口
- (void)getRightMenu{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
   
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/rightmenu",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  
                                  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
                                  
                                  
                                  [[NSUserDefaults standardUserDefaults] setObject:jsonData forKey:@"RightMenu"];
                                  
                                  
                                  
                                  _dataArray=result;
                                  [_tableView reloadData];
                                  [SVProgressHUD dismiss];

                              }];
}

#pragma mark - Table View Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray[section][@"Child"] count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 25)];
    UIImageView *bgImg = [[UIImageView alloc] initWithFrame:view.frame];
    [bgImg setImage:[UIImage imageNamed:@"headcell_bg.png"]];
    [view addSubview:bgImg];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 2, 200, 20)];
    [titleLabel setTextColor:[UIColor whiteColor]];
    titleLabel.text = _dataArray[section][@"MenuName"];
    [view addSubview:titleLabel];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
        cell.backgroundColor = [UIColor grayColor];
        cell.textLabel.textColor = [UIColor whiteColor];
    }
//    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URL_ROOT,_dataArray[indexPath.section][@"Child"][indexPath.row][@"IconURLStr"]]]];
    cell.textLabel.text = _dataArray[indexPath.section][@"Child"][indexPath.row][@"MenuName"];    
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIViewController *vc = nil;
    NSString *itemName = _dataArray[indexPath.section][@"Child"][indexPath.row][@"MenuName"];
    int menuID = [_dataArray[indexPath.section][@"Child"][indexPath.row][@"MenuID"] intValue];
    if (menuID==17) {//我的账户
        if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
            [SVProgressHUD showInfoWithStatus:@"请先登录"];
            vc = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        }
        else if ([[[GlobalData sharedGlobalData] userinfoDic][@"State"] intValue] == 0) {
            int userType = [[[GlobalData sharedGlobalData] userinfoDic][@"UserType"] intValue];
            if (userType == 0) {
                vc = [[OwnerCompleteViewController alloc] initWithNibName:nil bundle:nil];
            }
            else if (userType == 1) {
                vc = [[ShipperCompleteViewController alloc] initWithNibName:nil bundle:nil];
            }
            else if (userType == 2) {
                vc = [[LogisticsCompleteViewController alloc] initWithNibName:nil bundle:nil];
            }
        }else{
            vc = [[UserCenterViewController alloc] initWithNibName:nil bundle:nil];
        }
        
    }else if (menuID == 23){//退出
        if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
            [SVProgressHUD showInfoWithStatus:@"您还未登录"];
            return;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确认要退出登录吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert showWithCompletionHandler:^(NSInteger buttonIndex) {
            if (buttonIndex==1) {
                [[GlobalData sharedGlobalData] clearData];
                [self getAccountInfo];
                [SVProgressHUD showSuccessWithStatus:@"退出成功"];
                [_loginBtn setHidden:NO];
            }
        }];
        return;
    }
    else if (menuID == 14){//推荐分享
        vc = [[AppShareViewController alloc] initWithNibName:nil bundle:nil];
    }
    else if (menuID == 15){//意见反馈
        vc = [[FeedbackViewController alloc] initWithNibName:nil bundle:nil];
    }
    else if (menuID == 16){//周边应用
//        vc = [[FeedbackViewController alloc] initWithNibName:nil bundle:nil];
    }
    else if (menuID == 18 || menuID == 13){//新闻资讯 货运信息市场
        vc = [[NewsListViewController alloc] initWithNibName:nil bundle:nil];
        [(NewsListViewController *)vc setMenuID:menuID];
        [(BasicViewController *)vc setNavStr:itemName];
    }
    else if (menuID == 19){//关于我们
        vc = [[AboutUsViewController alloc] initWithNibName:nil bundle:nil];
    }
    else if (menuID == 20){//使用说明
//        vc = [[AboutUsViewController alloc] initWithNibName:nil bundle:nil];
        return;
    }
    else if (menuID == 21){//级别设定
//        vc = [[AboutUsViewController alloc] initWithNibName:nil bundle:nil];
        return;
    }else if (menuID == 22){//协议
        vc = [[ProtocolViewController alloc] initWithNibName:nil bundle:nil];
    }
    [(BasicViewController *)vc setNavStr:itemName];
    UINavigationController *menuController = (UINavigationController*)((AppDelegate*)[[UIApplication sharedApplication] delegate]).menuController;
    [menuController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
